package cn.lili.controller.payment;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
import cn.lili.modules.payment.service.SubMerchantInformationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 子商户信息管理中心
 *
 * @author Bulbasaur
 * @since 2020-02-25 14:10:16
 */
@RestController
@Api(tags = "用户积分历史接口")
@RequestMapping("/payment/sub-merchant")
@RequiredArgsConstructor
public class SubMerchantInformationController {

    private final SubMerchantInformationService merchantInformationService;


    @ApiOperation(value = "获取当前用户的商户信息")
    @GetMapping
    public ResultMessage<Object> getSubMerchantInformation(PaymentMethodEnum paymentMethod) {
        return ResultUtil.data(merchantInformationService.getSubMerchantInformation(paymentMethod));
    }

    @ApiOperation(value = "获取指定用户的商户信息")
    @GetMapping(value = "/{userId}")
    public ResultMessage<Object> getSubMerchantInformation(@PathVariable String userId, PaymentMethodEnum paymentMethod) {
        checkPermission();
        return ResultUtil.data(merchantInformationService.getSubMerchantInformationByUserId(userId, paymentMethod));
    }

    @ApiOperation(value = "获取当前用户的商户信息")
    @PostMapping
    public ResultMessage<Object> setSubMerchantInformation(PaymentMethodEnum paymentMethod, String subMerchantId) {
        return ResultUtil.data(merchantInformationService.setSubMerchantId(paymentMethod, subMerchantId));
    }

    @ApiOperation(value = "获取指定用户的商户信息")
    @PostMapping(value = "/{userId}")
    public ResultMessage<Object> setSubMerchantInformation(@PathVariable String userId, PaymentMethodEnum paymentMethod, String subMerchantId) {
        checkPermission();
        return ResultUtil.data(merchantInformationService.setSubMerchantIdByUserId(userId, paymentMethod, subMerchantId));
    }


    /**
     * 获取配置，或者修改他人配置需要判定权限
     * 检查权限
     */
    private void checkPermission() {
        if (!UserContext.getCurrentUser().getScene().equals(SceneEnums.MANAGER)) {
            throw new ServiceException(ResultCode.ERROR);
        }
    }
}
